package org.fall.service.impl;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUseException;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUseForUpdateException;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.util.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.AdminExample;
import org.fall.mapper.AdminMapper;
import org.fall.service.api.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin getAdminByUsername(String username, String password) {

        //1、根据登录账号查询Admin对象
        //创建AdminExample对象
        AdminExample adminExample = new AdminExample();

        //创建Criteria对象
        AdminExample.Criteria criteria = adminExample.createCriteria();

        //在Criteria对象中封装查询的条件
        criteria.andLoginAcctEqualTo(username);

        //调用AdminMapper的方法来查询
        List<Admin> adminList = adminMapper.selectByExample(adminExample);

        // 2、判断Admin对象是否为null或数据库数据不正常
        if (adminList == null || adminList.size() == 0) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        if (adminList.size() > 1) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        // 3、获取admin对象
        Admin admin = adminList.get(0);
        if (admin == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 4、如果admin对象不为null，则取出admin对象的密码
        String userPswdFromDb = admin.getUserPswd();

        // 5、对表单提交的密码进行md5加密
        String passwordForm = CrowdUtil.md5(password);

        // 6、对比两个密码
        // 因为两个密码都是对象，使用字符串的equals方法，如果存在空的密码则会触发空指针异常
        // 因此选用Objects.equals方法
        if (!Objects.equals(userPswdFromDb, passwordForm)) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 7、对比结果一致，返回admin对象
        return admin;
    }

    /**
     * @param keyword  关键字
     * @param pageNum  当前页码
     * @param pageSize 每一页显示的信息数量
     * @return 最后的pageInfo对象
     */
    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
        // 1、调用PageHelper的静态方法开启分页功能
        // 这里充分体现了PageHelper的“非侵入式”设计：原本要做的查询不必有任何修改
        PageHelper.startPage(pageNum, pageSize);

        // 2、执行查询
        List<Admin> adminList = adminMapper.selectAdminByKeyword(keyword);

        // 3、封装到PageInfo对象中
        return new PageInfo<>(adminList);

    }

    @Override
    public void remove(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public Admin getAdminById(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void update(Admin admin) {
        //"selecttive" 表示有选择的更新，对于null值的字段不更新
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception exception) {
            exception.printStackTrace();
            if (exception instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseForUpdateException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
            }
        }
    }

    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {
        // 1、根据adminId删除旧的关联关系数据
        adminMapper.deleteOldRelationship(adminId);

        // 2、根据roleIdList和adminId保存新的关联关系
        if (roleIdList != null && roleIdList.size() > 0) {
            adminMapper.insertNewRelationship(adminId, roleIdList);
        }
    }

    @Override
    public Admin getAdminByLoginAcct(String s) {

        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(s);

        List<Admin> adminList = adminMapper.selectByExample(adminExample);

        Admin admin = adminList.get(0);
        return admin;
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void saveAdmin(Admin admin) {

        //1、密码加密
        String userPswd = admin.getUserPswd();
//        String encode = CrowdUtil.md5(userPswd);
        String encode = passwordEncoder.encode(userPswd);
        admin.setUserPswd(encode);

        // 2、生成创建时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = simpleDateFormat.format(date);
        admin.setCreateTime(createTime);

        //执行保存
        try {
            adminMapper.insert(admin);
        } catch (Exception exception) {
            exception.printStackTrace();
            if (exception instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
            }
        }
    }

    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }


}
